package cn.yh.springsecurity.service.impl;

import cn.yh.springsecurity.common.AjaxResult;
import cn.yh.springsecurity.domain.entity.LoginUser;
import cn.yh.springsecurity.domain.entity.User;
import cn.yh.springsecurity.domain.query.LoginBody;
import cn.yh.springsecurity.mapper.UserMapper;
import cn.yh.springsecurity.service.IUserService;
import cn.yh.springsecurity.utils.RedisUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService{
    @Autowired
    private UserMapper userMapper;


    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public AjaxResult loginByUser(LoginBody loginBody) {


        //结合SpringSecurity的登录流程
        //1. UsernamePasswordAuthenticationToken 存储用户输入的用户名和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());

        //校验用户信息合法性 -> 调用LoadUserByUsernameService 方法
        //2. 调用AuthenticationManager 的 authenticate 方法进行身份验证
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authentication == null ){
            throw new RuntimeException("用户凭证不通过");
        }

        //获取用户凭证中的用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

//        if (loginUser == null) {
//            throw new RuntimeException("用户凭证已失效");
//        }
        //增加11redis缓存11
        redisUtils.setCacheObject("user:"+loginUser.getUser().getUserId(),loginUser,30,TimeUnit.MINUTES);

        //生成token
        String token = JWT.create().withClaim("userId", loginUser.getUser().getUserId())
                .sign(Algorithm.HMAC256("kfoaejglanldf-sfsjkgnalawd"));

        return AjaxResult.success("login success", token);
    }
}
